package com.shiliao.framework.base.ui;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.shiliao.framework.base.event.BaseMessageEvent;
import com.shiliao.framework.mvp.presenter.IBasePresenter;
import com.shiliao.framework.mvp.view.BaseView;
import com.shiliao.framework.ui.dilaog.YimeiLoadingDialog;
import com.shiliao.framework.ui.dilaog.YimeiToast;
import com.shiliao.framework.util.CommonUtil;
import com.shiliao.framework.util.LogUtil;
import com.shiliao.framework.util.SystemUtils;
import com.shiliao.framework.util.ToastUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.ButterKnife;

import static android.os.Looper.getMainLooper;

/**
 * Created by yx on 2017/6/2.
 */

public abstract class BaseFragment<T extends IBasePresenter> extends Fragment implements BaseView {

    public abstract int getLayoutId();

    private View mRootView;
    protected Activity mContext;
    private T presenter;
    protected boolean isInit = false;//判断view是否进行create和destroy，不影响变量的初始化和引用
    private YimeiToast yimeiToast;

    private YimeiLoadingDialog loadingDialog;

    protected void setPresenter(T presenter) {
        this.presenter = presenter;
    }

//    @Override
//    public void onSaveInstanceState(Bundle outState) {
//        //super.onSaveInstanceState(outState);
//    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        mContext = activity;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (mRootView == null) {
            mRootView = inflater.inflate(getLayoutId(), container, false);
            //绑定fragment
            ButterKnife.bind(this, mRootView);
        }
        initFragmentView();
        return mRootView;
    }

    protected View getRootView() {
        return mRootView;
    }

    protected void initFragmentView() {

    }

    protected void runOnUiThread(Runnable action) {
        if (mContext == null) {
            throw new NullPointerException("mContext is null");
        }
        mContext.runOnUiThread(action);
    }

    public static BaseFragment getClassFromName(String name) {
        try {
            BaseFragment fragment = (BaseFragment) Class.forName(name).newInstance();
            return fragment;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }

    public static BaseFragment newInstance(String fragmentName, Bundle bundle) {

        BaseFragment fragment = getClassFromName(fragmentName);
        if (bundle != null) {
            fragment.setArguments(bundle);
        }

        return fragment;
    }

    @Override
    public void onPause() {
        super.onPause();
        //LogUtil.e("yjl", getClass().getSimpleName() + "   onPause()  ");
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        isInit = false;
        //清除rootview
        if (mRootView != null && mRootView.getParent() != null) {
            ((ViewGroup) mRootView.getParent()).removeView(mRootView);
        }
        //LogUtil.e("yjl", getClass().getSimpleName() + "   onDestroyView()  ");
    }

    @Override
    public void onDestroy() {
        isInit = false;
        // LogUtil.e("yjl", getClass().getSimpleName() + "   onDestroy()  ");
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
        if (yimeiToast != null) {
            yimeiToast.dismiss();
            yimeiToast = null;
        }
        if (loadingDialog != null) {
            loadingDialog.dismiss();
            loadingDialog = null;
        }
        super.onDestroy();
    }

    /**
     * 必须使用标记符。这表明要在UI线程中处理
     */
    @Subscribe(threadMode = ThreadMode.MAIN, sticky = false)
    public synchronized void onEventMainThread(BaseMessageEvent event) {
        LogUtil.e(getClass().getSimpleName() + " onEventMainThread:" + event.eventId);
        if (event != null && event.eventId == 10003) {
            //           toLoginActivity();
//            LogUtil.e("yjl", getClass().getSimpleName() + " romove event:" + event.eventId);
            EventBus.getDefault().removeStickyEvent(event);
        }
    }

    /**
     * 必须使用标记符。这表明要在与发布线程相同的线程中处理
     */
    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onEvent(BaseMessageEvent event) {

    }

    /**
     * 必须使用标记符。这表明如果是在UI线程中发布，则在新线程中运行
     */
    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onEventBackgroundThread(BaseMessageEvent event) {

    }

    /**
     * 必须使用标记符。在新线程中运行
     */
    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onEventAsync(BaseMessageEvent event) {

    }


    /**
     * 只展示消息，并自动消失
     *
     * @param msg
     */
    protected void showToast(String msg) {
//        if (mContext != null) {
//            if (yimeiToast == null) {
//                yimeiToast = new YimeiToast(mContext);
//            }
//            yimeiToast.setMsg(msg);
//            yimeiToast.show(true);
//        }
        ToastUtils.toast(msg);
    }

    /**
     * 展示消息，自动消失
     *
     * @param msg
     * @param success
     */
    protected void showToast(String msg, boolean success) {
        showToast(msg, success, true);
    }

    /**
     * 显示toast
     *
     * @param msg       文字说明
     * @param success   成功状态还是失败状态
     * @param isDismiss 是否自动消失
     */
    protected void showToast(final String msg, final boolean success, final boolean isDismiss) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (mContext != null) {
                    if (yimeiToast == null) {
                        yimeiToast = new YimeiToast(mContext);
                    }
                    yimeiToast.setMsg(msg);
                    yimeiToast.setMsg(msg, success);
                    yimeiToast.show(isDismiss);
                }
            }
        });

    }

    @Override
    public void showLoadingView() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (mContext != null) {
                    //显示加载view
                    if (loadingDialog == null) {
                        loadingDialog = new YimeiLoadingDialog(mContext);
                    }
                    loadingDialog.setDialogCancelable(false);
                    loadingDialog.show(false);
                    Handler handler = new Handler(getMainLooper());
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            loadingDialog.dismiss();
                        }
                    }, 6 * 1000);
                }
            }
        });

    }

    @Override
    public void hideLoadingView() {
//        runOnUiThread(new Runnable() {
//            @Override
//            public void run() {
//                if (loadingDialog != null && loadingDialog.isShowing()) {
//                    loadingDialog.dismiss();
//                }
//            }
//        });
        Handler handler = new Handler(getMainLooper());
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (loadingDialog != null && loadingDialog.isShowing()) {
                    loadingDialog.dismiss();
                }
            }
        }, 1000);
    }

    //跳转至登录页面
//    @Subscribe(threadMode = ThreadMode.MAIN)
//    protected void onEventToLogin(BaseMessageEvent event) {
//        if (event != null && event.eventId == 10003) {
//            toLoginActivity();
//        }
//    }

    @Override
    public void toLoginActivity() {

        if (SystemUtils.getTopActivity().contains("WelcomeActivity")
                || SystemUtils.getTopActivity().contains("LoginActivity")) {
            return;
        }
        try {
            Intent intent = new Intent();
            intent.setClass(mContext, Class.forName("com.yimei.app.splash.WelcomeActivity"));
            //intent.setClass(mContext, Class.forName("com.yimei.app.activity.register.ui.LoginActivity"));
            //LogUtil.e("yjl", getClass().getSimpleName() + "====" + SystemUtils.getTopActivity());
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
//                    showToast("请先登录!");
                }
            });
            toActivity(intent);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    //show short toast 方法<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

    /**
     * 快捷显示short toast方法，需要long toast就用 Toast.makeText(string, Toast.LENGTH_LONG).show(); ---不常用所以这个类里不写
     *
     * @param stringResId
     */
    public void showShortToast(int stringResId) {
        CommonUtil.showShortToast(mContext, stringResId);
    }

    /**
     * 快捷显示short toast方法，需要long toast就用 Toast.makeText(string, Toast.LENGTH_LONG).show(); ---不常用所以这个类里不写
     *
     * @param string
     */
    public void showShortToast(String string) {
        CommonUtil.showShortToast(mContext, string);
    }
    //show short toast 方法>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>


    //启动新Activity方法<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

    /**
     * 打开新的Activity，向左滑入效果
     *
     * @param intent
     */
    public void toActivity(final Intent intent) {
        CommonUtil.toActivity(mContext, intent);
    }

    /**
     * 打开新的Activity
     *
     * @param intent
     * @param showAnimation
     */
    public void toActivity(final Intent intent, final boolean showAnimation) {
        CommonUtil.toActivity(mContext, intent, showAnimation);
    }

    /**
     * 打开新的Activity，向左滑入效果
     *
     * @param intent
     * @param requestCode
     */
    public void toActivity(final Intent intent, final int requestCode) {
        CommonUtil.toActivity(mContext, intent, requestCode);
    }

    /**
     * 打开新的Activity
     *
     * @param intent
     * @param requestCode
     * @param showAnimation
     */
    public void toActivity(final Intent intent, final int requestCode, final boolean showAnimation) {
        CommonUtil.toActivity(mContext, intent, requestCode, showAnimation);
    }
    //启动新Activity方法>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

    /**
     * 只是跳转的main activity
     * 不做子页面切换
     */
    protected void toMainActivity() {
        toMainActivity(-1, -1);
    }

    /**
     * 跳转main activity的某个子页面
     *
     * @param pos
     */
    protected void toMainActivity(int pos) {
        toMainActivity(pos, -1);
    }

    /**
     * 跳转main activity
     * 可以切换子页面和 子页面的二级页面
     *
     * @param pos       子页面
     * @param childView 子页面的二级页面
     */
    protected synchronized void toMainActivity(int pos, int childView) {
        try {
            Intent intent = new Intent();
            Bundle bundle = new Bundle();
            if (pos >= 0) {
                bundle.putInt("pos", pos);
            }
            if (childView >= 0) {
                bundle.putInt("childView", childView);
            }
            intent.putExtras(bundle);
            intent.setClass(mContext, Class.forName("com.yimei.app.activity.MainActivity"));
            toActivity(intent);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}
